package com.gyg.程序员面试金典;

/**
 * 面试题 01.03. URL化
 */
public class T01_03 {
    /**
     * 面试题 01.03. URL化
     *
     * @param S
     * @param length
     * @return
     */
    public String replaceSpaces(String S, int length) {
        String substring = S.substring(0, length);
        char[] chars = substring.toCharArray();
        int a = 0, maxLength = 0, j = 0;
        for (char cs : chars) {
            if (cs == ' ') {
                a++;
            }
        }
        maxLength = length + a * 2;
        char[] result = new char[maxLength];
        for (int i = 0; i < length; i++) {
            if (chars[i] == ' ') {
                result[j++] = '%';
                result[j++] = '2';
                result[j++] = '0';
            } else {
                result[j++] = chars[i];
            }
        }
        return new String(result);
    }
}
